// pages/apply/apply.js
var util = require("../../utils/utils.js");
var app = getApp()
Page({
  data: {
    orderNo: null,
    choss: true,
    loading:false, //是否隐藏加载窗
  },
  // form表单
  formSubmit: function(e) {
    // console.log("======================================================",e)
    let swith = this.data.choss; //获取是否已经阅读并且接受协议
    let sex = this.data.sex; //获取学生的性别
    let types = this.data.description.isFamily; //获取是否家庭课程  1是0否
    let params = {
      productId: this.data.description.id,
      channel: 'WeiXin',
      formId: e.detail.formId,
      childIdcard: e.detail.value.childIdcard, //孩子身份证号码
      emerMobile: e.detail.value.emerMobile, //孩子电话
      childName: e.detail.value.childName, //孩子姓名
      childGrade: e.detail.value.childGrade, //孩子班级
      childSchoolName: e.detail.value.childSchoolName, //孩子学校
      childSex: sex //孩子性别
    }
    // console.log(params)
    if(types == 1){
      let guardian = this.data.farmlist;
      let arr = [];
      for (let a = 0; a < guardian.length;a++){
        if (guardian[a].choss == true){
          arr.push(guardian[a].id)
        }
      }
      let join = arr.join(",");
      // console.log(join)
      params.guardianIds = join
    }
    if(types ==1 && !params.guardianIds){
      wx.showToast({
        title: '请选择监护人',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (types == 1 && !params.childGrade) {
      wx.showToast({
        title: '请填写孩子班级',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (types == 1 && !params.childSchoolName) {
      wx.showToast({
        title: '请填写孩子学习',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (!params.childIdcard){
      // console.log(params.childIdcard)
      wx.showToast({
        title: '小孩身份证号码不能为空',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (!params.childSex) {
      wx.showToast({
        title: '小孩性别不能为空',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (!params.emerMobile) {
      wx.showToast({
        title: '联系电话不能为空',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (!params.childName) {
      wx.showToast({
        title: '小孩姓名不能为空',
        icon: 'none',
        duration: 1000
      });
      return;
    }

    if (!swith) {
      wx.showToast({
        title: '请阅读并接受协议',
        icon: 'none',
        duration: 1000
      });
      return;
    }

    this.pay(params);

  },
  formReset: function() {
    // console.log('form发生了reset事件')
  },
  /**
   * 获取学生性别
   */
  radioChange: function(e) {
    // console.log(e.detail.value);
    let that = this;
    that.setData({
      sex: e.detail.value
    })
  },
  /**
   * 获取监护人姓名
   */
  farmname:function(e){
    this.setData({
      guardianName: e.detail.value
    })
  },
  /**获取监护人身份证 */
  farmid: function (e) {
    this.setData({
      guardianIdcard: e.detail.value
    })
  },
  /**
   * 监护人身份选择
   */
  radioChang: function(e) {
    let that = this;
    that.setData({
      guardianRelation: e.detail.value
    })
  },
  /**
   * 新增监护人信息弹窗
   */
  shows: function() {
    let that = this;
    this.setData({
      tang: !that.data.tang,
      guardianRelation: "",
      guardianIdcard: "",
      guardianName: "",
    })
  },
  /**
   * 提交监护人信息
   */
  give: function() {
    let that = this;
    let guardianName = this.data.guardianName; //家长姓名
    let guardianIdcard = this.data.guardianIdcard; //家长身份证号码
    let guardianRelation = this.data.guardianRelation; //家长身份
    let types = wx.getStorageSync("changes"); //获取是否修改信息 0位修改 1不是修改
    let id = wx.getStorageSync("id");
    if (!guardianName){
      wx.showToast({
        title: '请填写家长姓名',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (!guardianIdcard) {
      wx.showToast({
        title: '请填写家长身份证号码',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (!guardianRelation) {
      wx.showToast({
        title: '请选择家长身份',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    // console.log(types)
    if (types == "0") {
      wx.request({
        url: app.httpUrl +'/guardian/updateGuardian',
        header: {
          'xcx-xtoken': app.globalData.openid,
          'content-type': 'application/json' // 默认值
        },
        method: "POST",
        data: {
          guardianName: guardianName,
          guardianIdcard: guardianIdcard,
          guardianRelation: guardianRelation,
          id:id,
        },
        success: function(res) {
          // console.log(res.data.data)
          if (res.data.code == "000") {
            wx.showToast({
              title: '修改成功',
            })
            that.setData({
              tang: !that.data.tang,
              
            })
            wx.removeStorageSync("changes")
            wx.removeStorageSync("id")
            that.getfaim()
          }
        }
      })
    } else {
      wx.request({
        url: app.httpUrl + '/guardian/addGuardian',
        header: {
          'xcx-xtoken': app.globalData.openid,
          'content-type': 'application/json' // 默认值
        },
        method: "POST",
        data: {
          guardianName: guardianName,
          guardianIdcard: guardianIdcard,
          guardianRelation: guardianRelation
        },
        success: function(res) {
          // console.log(res)
          if (res.data.code == "000"){
            wx.showToast({
              title: '提交成功',
            })
            that.setData({
              tang:!that.data.tang
            })
            wx.removeStorageSync("changes")
            that.getfaim()
          }
        }
      })
    }

  },
  /**
   * 选取监护人
   */
  choss:function(e){
    let that = this;
    let index = e.currentTarget.dataset.index;
    let list  = this.data.farmlist;
    if(!list[index].choss){
      list[index].choss = true
      that.setData({
        farmlist:list,
        loading:true,
      },()=>{
        wx.hideLoading()
      })
    }else{
      list[index].choss = false
      that.setData({
        farmlist: list,
        loading: true
      },()=>{
        wx.hideLoading()
      })
    }
  },
  /**
   * 获取监护人信息
   */
  getfaim: function() {
    let that = this;
    wx.request({
      url: app.httpUrl + '/guardian/queryList',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: function(res) {
        // console.log(res.data.data)
        that.setData({
          farmlist:res.data.data,
          loading: true,
        },()=>{
          wx.hideLoading()
        })
      }
    })
  },
  /**
   * 查询监护人信息
   */
  getbobyfarm: function(e) {
    let id = e.currentTarget.dataset.id;
    let that = this;
    wx.setStorageSync("changes", 0)
    wx.setStorageSync("id", id)
    that.setData({
      tang: !that.data.tang
    })
    wx.request({
      url: app.httpUrl + '/guardian/queryGuardian/' + id,
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: function(res) {
        // console.log(res.data.data)
        that.setData({
          guardianRelation:res.data.data.guardianRelation,
          guardianName: res.data.data.guardianName,
          guardianIdcard: res.data.data.guardianIdcard
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    _this.setData({
      tang: true,
    })
    wx.showLoading({
      title: '加载中...',
      mask:true,
    })
    _this.getfaim()
    // 头部数据接口
    wx.request({
      url: app.httpUrl +'/course/queryCourseDetail/' + options.productid,
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: (res) => {
        let description = res.data.data;
        // console.log(description)
        description.startDate = util.formatDate(description.startDate, 'Y年M月D日');
        description.endDate = util.formatDate(description.endDate, 'Y年M月D日');
        _this.setData({
          description: description
        })
      }
    })
  },
  pay: function(params) {
    if (this.data.orderNo != null) {
      this.paySign(this.data.orderNo);
    } else {
      this.createSign(params);
    }
  },
  createSign: function(data) {
    let that = this;
    // 下单接口
    wx.request({
      url: app.httpUrl +'/course/order/createSign',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: data,
      method: "POST",
      success: (res) => {
        var signData = res.data.data;
        if (res.data.code != '000') {
          wx.showToast({
            title: '下单失败，请刷新再试',
            icon: 'none',
            duration: 2000
          });
          return;
        }
        that.setData({
          orderNo: signData.orderNo
        });
        this.payment(signData);
      }
    })
  },
  /**
   * 阻止底部滑动
   */
  preventTouchMove:function(e){

  },
  // 同意协议
  chosses: function() {
    let that = this;
    let chosses = this.data.choss; //获取开关
    chosses = !chosses;
    this.setData({
      choss: chosses,
    })
  },
  // 跳转协议
  jump: function() {
    wx.navigateTo({
      url: '/pages/duty/duty',
    })
  },
  agreementTab: function() {
    this.setData({
      isShowAgreement: this.data.isShowAgreement ? false : true
    })
  },
  paySign: function(orderNo) {
    wx.request({
      url: app.httpUrl +'/pay/sign',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        orderNo: orderNo
      },
      method: "POST",
      success: (res) => {
        var signData = res.data.data;
        this.payment(signData);
      }
    })
  },
  payment: function(signData) {
    var that = this;
    wx.requestPayment({
      'timeStamp': signData.timeStamp,
      'nonceStr': signData.nonceStr,
      'package': signData.packages,
      'signType': 'MD5',
      'paySign': signData.paySign,
      success: function(res) {
        that.setData({
          orderNo: null
        });
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        });

        wx.navigateTo({
          url: '/pages/orderDetail/orderDetail?orderNo=' + signData.orderNo,
          success: function() {
            // console.log('success');
            this.onLoad();
          }
        })

      },
      fail: function(res) {
        wx.navigateTo({
          url: '/pages/orderDetail/orderDetail?orderNo=' + signData.orderNo,
          success: function() {

          }
        })
      },

      'complete': function(res) {
        // console.log(res);
      }

    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})